<?php  
class ControllerUDEMCommonLogin extends Controller { 
	public function index(){
		$tokenAvail = isset($this->request->get['token']);
		$tokenSessionAvail = isset($this->session->data['token']);
		
		$msg = '';
		
		//user has logged in.
		if ($this->user->isLogged() && $tokenAvail && ($this->request->get['token'] == $this->session->data['token'])) {
			$this->data['eMsg'] = 'has login';
		}
		
		//do login
		if (!isset($this->data['eMsg']) && ($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { 
			$this->session->data['token'] = md5(mt_rand());
		
			$msg = 'true';
			$this->response->addHeader('token: ' . $this->session->data['token']);
		}
		
		
		//$this->data['eMsg'] = $this->error->normalError('error');
		if(isset($this->data['eMsg'])){
			echo $this->data['eMsg'];
			//$this->template = 'ude/common/error.tpl';
		} else {
			echo $msg;
			//$this->data['msg'] = $msg;
			//$this->template = 'ude/common/login.tpl';
		}
	
		//$this->response->setOutput($this->render());
	}
	
	protected function validate() {
		if(!isset($this->request->post['username']) || !isset($this->request->post['password'])){
			$this->data['eMsg'] = $this->error->normalError('username or pwd can not be empty');
			return false;
		} else if (!$this->user->login($this->request->post['username'], $this->request->post['password'])){
			$this->data['eMsg'] = $this->error->normalError('username or pwd incorrect');
			
			return false;
		}
		
		return true;
		
	}
}
?>